#include "BlockQueue.hpp"
#include "Task.hpp"
#include <ctime>
#include <unistd.h>

void *Consumer(void *args)
{
    BlockQueue<Task> *q = static_cast< BlockQueue<Task> *>(args);
    while (true)
    {
        Task t = q->pop();
        t();
        //usleep(1);
        cout<<"处理了一个任务："<<t.GetResult()<<", thread id :"<<pthread_self()<<endl;
        //sleep(1);
    }
    return nullptr;
}

void *Productor(void *args)
{
    BlockQueue<Task> *q = static_cast< BlockQueue<Task> *>(args);
    while (true)
    {
        int data1 = rand() % 10 + 1;
        int data2 = rand() % 10;
        char oper = opers[rand() % opers.size()];
        usleep(1);
        Task t(data1, data2, oper);
        q->push(t);
        cout<<"发送了一个任务 : "<<t.GetTask()<<", thread id :"<<pthread_self()<<endl;
        sleep(1);
    }
    return nullptr;
}

int main()
{
    srand(time(nullptr) ^ getpid());
    BlockQueue<Task> q;
    pthread_t c[3], p[5];
    for (int i = 0; i < 3; i++)
    {
        pthread_create(c + i, nullptr, Consumer, &q);
    }
    for (int i = 0; i < 5; i++)
    {
        pthread_create(p + i, nullptr, Productor, &q);
    }
    for (auto x : c)
    {
        pthread_join(x,nullptr);
    }
    for (auto x : p)
    {
        pthread_join(x,nullptr);
    }
    return 0;
}